package com.pan.behavioral.iterator.itr.impl;

import com.pan.behavioral.iterator.itr.MyCollection;
import com.pan.behavioral.iterator.itr.MyIterator;

import java.util.function.Consumer;

public class MyLinkedList<T> implements MyCollection<T> {

    private class Node<T>{
        public Node<T> previous;
        public T value;
        Node<T> next;
    }
    private Node<T> current ;
    private Node<T> headNode;
    private Node<T> tailNode;

    public boolean isHead(){
        return current == headNode ;
    }
    public boolean isTail(){
        return current == tailNode ;
    }

    public MyLinkedList() {
        this.headNode = new Node<>();
        this.tailNode = new Node<>();
        current = headNode;
        current.next = tailNode;
        tailNode.previous = current;
    }

    @Override
    public MyIterator<T> iterator() {
        return new LinkedListIterator();
    }
    private class LinkedListIterator implements MyIterator{
        private Node cursor;

        public LinkedListIterator() {
            cursor = headNode;
        }

        @Override
        public boolean hasNext() {
            return cursor.next!=tailNode;
        }

        @Override
        public Object next() {
            cursor = cursor.next;
            return cursor.value;
        }

        @Override
        public void remove() {
            if (cursor.next == tailNode||cursor == tailNode){
                throw new RuntimeException("是尾节点，无法删除");
            }
            Node pre = cursor;
            Node nxt = cursor.next.next;
            if (cursor.next == current){
                current = cursor;
            }
            cursor = cursor.next;
            pre.next = nxt;
            nxt.previous = pre;

        }

        @Override
        public void forEachRemaining(Consumer action) {
            for (;hasNext();){
                action.accept(next());
            }
        }
    }

    @Override
    public void add(T element) {
        Node<T> newNode = new Node<>();
        newNode.value = element;

        Node nxtNode = current.next;

        newNode.previous = current;
        newNode.next = nxtNode;

        current.next = newNode;
        nxtNode.previous = newNode;
        current = newNode;
    }


}
